import sqlite3
import pandas as pd
import json
import math


# noinspection NonAsciiCharacters
class Pf:  # production_formula
    def __int__(self, pf: dict):
        self.序号 = pf['序号']
        self.材料 = pf['材料']
        self.设备 = pf['设备']
        self.序号 = pf['序号']

    序号 = 0
    设备 = ''


class Db:
    def __init__(self):
        self._conn = sqlite3.connect('sf_data.db')
        self.cursor = self._conn.cursor()

    def close(self):
        self._conn.close()

    def query_formulas(self, product):
        self.cursor.execute(f'select * from production_formula where 产品 = ?', (product,))
        results = self.cursor.fetchall()
        formulas = []
        for formula in results:
            formulas.append({
                '序号': formula[0] + 1,
                '设备': formula[1],
                '产品': formula[2],
                '产能': formula[3],
                '副产物': formula[4],
                '副产能': formula[5],
                '耗电': formula[6],
                '材料': json.loads(formula[7])
            })
        return formulas

    def is_raw_material(self, material):
        self.cursor.execute(f'select count(*) from raw_material where 名称 = ?', (material,))
        return self.cursor.fetchone()[0] > 0


class Production:

    def __init__(self, db):
        self.db = db

    def get_materials(self, product, number):
        plans = self.db.query_formulas(product)
        for plan in plans:
            plan['需求量'] = number
            output = plan['产能'] if plan['产品'] == product else plan['副产能']
            plan['设备数'] = plan['需求量'] / output
            for ma, ma_ct in plan['材料'].items():
                plan['材料'][ma] = ma_ct * plan['设备数']
                if not self.db.is_raw_material(ma):
                    plan['材料'][ma] = self.get_materials(ma, plan['材料'][ma])
        return plans

    def unfold_plan(self, plans):
        for plan in plans:
            return plan



if __name__ == '__main__':
    db = Db()
    p = Production(db)
    m = p.get_materials('钢梁', 75)
    print(json.dumps(m, indent=2, ensure_ascii=False))
    with open("plan.json", "w") as f:
        json.dump(m, f, ensure_ascii=False, indent=2)
    db.close()
    pass
